import socket
import multiprocessing
import re
import mini_wsgi_frame


class WSGIServer(object):

    def __init__(self):

        """用来完成整体的控制"""
        # 1.创建套接字
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 2.绑定
        self.tcp_server_socket.bind(("192.168.3.86", 7232))
        # 3.变为监听套接字
        self.tcp_server_socket.listen(128)

    def server_client(self,new_socket):
        """为这个客户端返回数据"""
        # # 组织相应 头信息(header)
        # 1.接收浏览器发送过来的请求，即 http请求
        # GET / HTTP/1.1
        # ....
        request = new_socket.recv(1024).decode("utf-8")
        # print(request)

        request_lines = request.splitlines()
        print("")
        print(">"*20)
        print(request_lines)
        print("<" * 20)

        # GET /index.html HTTP/1.1
        # get post put del
        file_name = ""
        ret = re.match(r"[^/]+(/[^ ]*)",request_lines[0])

        if ret:

            file_name = ret.group(1)

            print("file_name=%s" % file_name)

            print("*"*50,file_name)
            if file_name == "/":
                file_name = "/index.html"

        # 2.返回http格式的数据，给浏览器
        # 2.1、准备发送给浏览器的数据---header

        if not file_name.endswith(".html"):

            try:
                f = open("./static"+file_name,"rb")
            except:
                response = "HTTP/1.1 404 NOT FOUND\r\n"
                response += "\r\n"
                response += "----file not found"
                new_socket.send(response.encode("utf-8"))
            else:

                print("-----------OK------------")

                html_content = f.read()
                f.close()

                response = "HTTP/1.1 200 OK\r\n"  # 200表示找到这个资源
                response += "\r\n"  # 用一个空的行与body进行隔开
                # 2.2、准备发送给浏览器的数据 ---body
                # 将response的header发送给浏览器
                new_socket.send(response.encode("utf-8"))
                # 将response的 body 发送给浏览器
                new_socket.send(html_content)
        else:

            # 2.2 如果是以 .py 结尾请求就认为是动态资源请求
            evn = dict()
            evn["PATH_INFO"] = file_name
            body = mini_wsgi_frame.mini_swgi_frame.application(evn,self.set_response_header)

            header = "HTTP/1.1 %s\r\n"%self.status  # 200表示找到这个资源
            for temp in self.headers:

                header += "%s:%s\r\n"%(temp[0],temp[1])

            header += "\r\n"  # 用一个空的行与body进行隔开

            response = header + body

            # 准备发送给浏览器的数据 ---body
            # 将response发送给浏览器
            new_socket.send(response.encode("utf-8"))

        # 3.关闭套接字
        new_socket.close()

    def set_response_header(self,status,headers):
        self.status = status
        self.headers = [("server","mini_web v9.2")]
        self.headers += headers


    def run_server(self):

        while True:
            # 4.等待客户端的链接
            new_socket, client_addr = self.tcp_server_socket.accept()

            # 5.开辟一个进程为这个客户端服务
            p = multiprocessing.Process(target=self.server_client,args=(new_socket,))
            p.start()

            new_socket.close()

        # 6.关闭监听的套接字
        tcp_server_socket.close()


def main():
    wsgi_server = WSGIServer()
    wsgi_server.run_server()


if __name__ == '__main__':
     main()